package com.summer.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PicDownloader {
	
	private final BlockingQueue<String> workerQueue = new ArrayBlockingQueue<String>(1);
	private int poolSize = 3;
	
	ExecutorService fixedThreadPool = Executors.newFixedThreadPool(poolSize);
	
	public PicDownloader(){
		for(int index=0;index<poolSize;index++){
			fixedThreadPool.execute(new DownloaderProcess());
		}
	}
	
	public void submit(String task){
		try{
			workerQueue.put(task);
		}catch(InterruptedException ex){
			Thread.currentThread().interrupt();
		}
	}
	
	protected boolean downloader(String task){
		System.out.println("下载了"+task);
		return true;
	}
	
	private class DownloaderProcess extends Thread{
		
		private volatile boolean isRun = true;
		private volatile boolean isPause = true;
		private final Object lock = new Object[0];
		
		public void pause(){
			isPause = true;
		}
		public void start(){
			isPause = false;
			lock.notify();
		}
		
		Callback callBack = new Callback() {
			
			@Override
			public void pauseNotify() {
				
			}
			
			@Override
			public void errorNotify() {
			}
			
			@Override
			public void completeNotify() {
				// TODO Auto-generated method stub
				
			}
		};
		
		@Override
		public void run() {
			String task ;
			
			while(isRun){
				try {
					task = workerQueue.take();
					if(isPause){
						callBack.pauseNotify();
						synchronized (lock) {lock.wait();}
					}
					if(downloader(task)){
						callBack.completeNotify();
					}else{
						callBack.errorNotify();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private interface Callback {
		public void pauseNotify();
		public void errorNotify();
		public void completeNotify();
	}
	
}
